package com.baibei.order.settlement;

import android.content.Context;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.SparseArray;

import com.baibei.basic.BasicPresenterImpl;
import com.baibei.ebec.quotation.AppQuotationFilter;
import com.baibei.ebec.quotation.QuotationManager;
import com.baibei.ebec.quotation.event.IQuotationEvent;
import com.baibei.ebec.quotation.event.ITradeEvent;
import com.baibei.ebec.sdk.ApiFactory;
import com.baibei.ebec.sdk.ITradeApi;
import com.baibei.ebec.sdk.IUserApi;
import com.baibei.model.AddressInfo;
import com.baibei.model.BalanceInfo;
import com.baibei.model.BuyDirection;
import com.baibei.model.OrderInfo;
import com.baibei.model.QuotationInfo;
import com.baibei.model.TradeWebSocketInfo;
import com.baibei.quotation.QuotationFilter;
import com.baibei.sdk.ApiDefaultObserver;
import com.baibei.sdk.Empty;
import com.rae.swift.Rx;

import org.greenrobot.eventbus.Subscribe;

import java.util.List;

/**
 * 补款取货
 * Created by ChenRui on 2017/8/11 0011 16:36.
 */
public class SettlementPresenterImpl extends BasicPresenterImpl<SettlementContract.View> implements SettlementContract.Presenter, IQuotationEvent, ITradeEvent {

    IUserApi mUserApi;
    ITradeApi mTradeApi;
    private OrderInfo mOrderInfo;
    private double mAmount;
    private BalanceInfo mBalanceInfo;
    private CountDownTimer mCountDownTimer;

    public SettlementPresenterImpl(Context context, SettlementContract.View view) {
        super(context, view);
        mUserApi = ApiFactory.getInstance().getUserApi();
        mTradeApi = ApiFactory.getInstance().getTradeApi();

        // 注册行情

        QuotationFilter filter = new QuotationFilter(AppQuotationFilter.ACTION_TRADE_CLOSED);
        filter.addAction(QuotationFilter.ACTION_QUOTATION_PRODUCT);
        QuotationManager.getInstance().register(this, filter);

        // webSocket 超时
        mCountDownTimer = new CountDownTimer(5000, 1000) {
            @Override
            public void onTick(long l) {
            }

            @Override
            public void onFinish() {
                mView.onTradeTimeout();
            }
        };
    }

    @Override
    public void destroy() {
        QuotationManager.getInstance().unregister(this);
        super.destroy();
    }

    @Override
    public void start() {
        super.start();
        mOrderInfo = mView.getOrderInfo();
        updateAmount();

        // 加载收货地址
        createObservable(mUserApi.getAddress("1"))
                .subscribe(new ApiDefaultObserver<List<AddressInfo>>() {
                    @Override
                    protected void onError(String s) {
                        mView.onEmptyAddress();
                    }

                    @Override
                    protected void accept(List<AddressInfo> data) {
                        if (Rx.isEmpty(data)) {
                            mView.onEmptyAddress();
                            return;
                        }
                        mView.onLoadDefaultAddress(data.get(0));
                    }
                });
        resume();


    }

    @Override
    public void resume() {
        // 加载余额
        createObservable(mUserApi.getBalanceInfo())
                .subscribe(new ApiDefaultObserver<BalanceInfo>() {

                    @Override
                    protected void onError(String s) {
                        mView.onLoadBalanceFailed(s);
                    }

                    @Override
                    protected void accept(BalanceInfo balanceInfo) {
                        mBalanceInfo = balanceInfo;
                        mView.onLoadBalanceInfo(balanceInfo);
                    }
                });
    }


    @Override
    @Subscribe
    public void onEvent(SparseArray<QuotationInfo> quotations) {
        if (mOrderInfo == null || mView == null) return;
        String productId = mOrderInfo.getProductid();
        QuotationInfo quotationInfo = quotations.get(Rx.parseInt(productId));
        if (quotationInfo == null) return;

        // 更新价格
        mOrderInfo.setLast(quotationInfo.getMarketPrice());
        mView.onLoadOrderInfo(mOrderInfo);


        updateAmount();
    }

    //记录金额
    private void updateAmount() {
        mAmount = mOrderInfo.getBuyprice() * mOrderInfo.getCount() - mOrderInfo.getBuyMoney();
        if (mOrderInfo.getBuydirection() == BuyDirection.DIRECTION_SETTLEMENT_PRICE) {
            mAmount = mOrderInfo.getLast() * mOrderInfo.getCount() - mOrderInfo.getBuyMoney();
        }
    }


    @Override
    public void pay() {
        String addressId = mView.getAddressId();
        if (TextUtils.isEmpty(addressId)) {
            mView.onPayFailed("请先添加收货地址");
            return;
        }

        // 余额不足
        if (mBalanceInfo == null || mAmount < 0 || mBalanceInfo.getBalance() - mAmount <= 0) {
            mView.onNotMoney();
            return;
        }


        createObservable(mTradeApi.settlement(mView.getOrderInfo().getOrderid(), mView.getOrderInfo().getArea(), addressId))
                .subscribe(new ApiDefaultObserver<Empty>() {
                    @Override
                    protected void onError(String s) {
                        mView.onPayFailed(s);
                    }

                    @Override
                    protected void accept(Empty empty) {
                        mCountDownTimer.cancel();
                        mCountDownTimer.start();
                    }
                });

    }

    @Override
    public double getAmount() {
        return mAmount;
    }

    @Override
    @Subscribe
    public void onEvent(TradeWebSocketInfo tradeInfo) {
        mCountDownTimer.cancel();
        if ("CODE_CLOSE_SUCCESS".equalsIgnoreCase(tradeInfo.getCode())) {
            mView.onPaySuccess();
        }
        if ("CODE_CLOSE_FAIL".equalsIgnoreCase(tradeInfo.getCode())) {
            //余额不足
            if ("1047".equals(tradeInfo.getErrorCode())) {
                mView.onNotMoney();
            } else {
                mView.onPayFailed("补款取货响应失败，失败原因：" + tradeInfo.getMsg() + "，请前往订单中心查看最新结果");
            }
        }
    }
}
